package Produce_Consume.Use_Lock.StorageDemo;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Kevin
 * @date 2020/3/28 11:34
 */
public class Storage {
    //仓库容量
    private final int MAX_SIZE = 10;
    //仓库存储的载体
    private LinkedList<Object> list = new LinkedList<>();
    //锁
    private final Lock lock = new ReentrantLock();
    //仓库满的条件变量
    private final Condition NotFull = lock.newCondition();
    //仓库空的条件变量
    private final Condition NotEmpty = lock.newCondition();

    public void produce() {
        //获得锁
        lock.lock();
        while (list.size() + 1 > MAX_SIZE) {
            System.out.println("【生产者" + Thread.currentThread().getName()
                    + "】仓库已满");
            try {
                NotFull.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        list.add(new Object());
        System.out.println("【生产者" + Thread.currentThread().getName()
                + "】生产一个产品，现库存" + list.size());
        NotEmpty.signal();
        lock.unlock();

    }

    public void consume() {
        //获得锁
        lock.lock();
        while (list.size() == 0) {
            System.out.println("【消费者" + Thread.currentThread().getName()
                    + "】仓库为空");
            try {
                NotEmpty.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        list.remove();
        System.out.println("【消费者" + Thread.currentThread().getName()
                + "】消费一个产品，现库存" + list.size());
        NotFull.signal();
        lock.unlock();

    }
}
